package org.summer.generator.channel;


import org.summer.generator.log.Logger;
import org.summer.generator.log.LoggerManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 默认文件写入通道
 */
public class DefaultFileWriterChannel implements FileWriterChannel {
    private static final Logger log = LoggerManager.getLogger(DefaultFileWriterChannel.class);
    private final FileOutputStream os;
    private final FileChannel channel;

    public DefaultFileWriterChannel(File file) throws FileNotFoundException {
        this.os = new FileOutputStream(file);
        this.channel = os.getChannel();
    }

    @Override
    public void writer(String content) {
        try {
            channel.write(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            log.error("文件通道将内容写入文件时候出现错误: %s".formatted(content),e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void beforeClose() {

    }

    @Override
    public void close() throws Exception {
            channel.close();
            os.close();
    }
}
